<template>
  <div class="table-container pull-chheight">
    <basic-container>
      <avue-crud :option="tableOption"
                 v-model="mainBeanModel"
                 :data="tableData"
                 :table-loading="tableLoading"
                 :row-class-name="tableRowClassName"
                 :page="pageBeanModel"
                 ref="crud"
                 @row-save="handleSave"
                 @row-update="handleUpdate"
                 @row-del="handleDel"
                 @refresh-change="handlerefreshChange"
                 @current-change="handlePageCurrentChange"
                 @size-change="handlePageSizeChange"
                 @search-change="handleSearchChange"
                 @selection-change="handleSelectionChange">
        <template slot="menuLeft">
          <el-button type="primary"
                     icon="el-icon-edit"
                     size="small"
                     v-if="permission.sys_base_role_update"
                     @click="handleRowEdit">编 辑</el-button>
          <el-button type="primary"
                     icon="el-icon-delete"
                     size="small"
                     v-if="permission.sys_base_role_delete"
                     @click="handleRowDel">删 除</el-button>

          <el-button @click="toSetRoleMenu()"
                     icon="el-icon-menu"
                     v-if="permission.sys_base_role_setmenu"
                     size="small">{{ $t('system.SysRole.setMenuBtnTxt')}}</el-button>

          <el-button @click="toSetRolePermission()"
                     icon="el-icon-menu"
                     v-if="permission.sys_base_role_setperm"
                     size="small">{{ $t('system.SysRole.setPermBtnTxt')}}</el-button>
        </template>
        <template slot="menuRight">
          <el-button type="primary"
                     icon="el-icon-edit"
                     size="small"
                     circle
                     v-if="permission.sys_base_role_update"
                     @click="handleRowEdit"></el-button>
          <el-button type="danger"
                     icon="el-icon-delete"
                     circle
                     size="small"
                     v-if="permission.sys_base_role_delete"
                     @click="handleRowDel"></el-button>
        </template>
      </avue-crud>
    </basic-container>

    <el-dialog title="菜单"
               :visible.sync="userMenuParamBean.showDialog"
               width="40%">
      <el-tree :data="allSysMenuTreeData"
               :props="userMenuTreeProps"
               :default-checked-keys="userMenuParamBean.selectedItems"
               :default-expanded-keys="userMenuParamBean.selectedItems"
               @check-change="handleUserMenuCheckChange"
               show-checkbox
               node-key="id">
      </el-tree>
      <span slot="footer"
            class="dialog-footer">
        <el-button type="primary"
                   @click="handleUserMenuUpdate">{{ $t('commHandle.saveBtnTxt')}}</el-button>
      </span>
    </el-dialog>

    <el-dialog title="权限"
               :visible.sync="rolePermissionParamBean.showDialog"
               width="40%">
      <el-tree :data="allRolePermissionData"
               :props="rolePermissionTreeProps"
               :default-checked-keys="rolePermissionParamBean.selectedItems"
               :default-expanded-keys="rolePermissionParamBean.selectedItems"
               @check-change="handleRolePermissionCheckChange"
               show-checkbox
               node-key="id">
      </el-tree>
      <span slot="footer"
            class="dialog-footer">
        <el-button type="primary"
                   @click="handleRolePermissionUpdate">{{ $t('commHandle.saveBtnTxt')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import tableOption from '@/views/system/role/roleOption';
import { parseTime } from '@/util/filters'
import { validatenull } from '@/util/validate';
import { readSystemRoleByPage,addSystemRole,editSystemRole,delSystemRole,readRoleMenu,setRoleMenu,readRolePermission,setRolePermission } from '@/views/system/role/roleApi'
import { readSystemMenuByTree,readSystemMenuWhtiBtnsByTree } from '@/views/system/menu/menuApi'

export default {
  name: 'table',
  data () {
    return {
      tableSearch: {},
      tableOption: tableOption, //表格设置属性
      tableData: [], //表格的数据
      tableRow: {},
      tableLoading: false,
      tabelObj: {},
      mainBeanModel: {},
      pageBeanModel: {
        total: 0, //总页数
        currentPage: 1, //当前页数
        pageSize: 10, //每页显示多少条
      },
      //菜单
      allSysMenuTreeData: [],//系统所有菜单树数据
      userMenuTreeProps: {
        children: 'children',
        label: 'menuName'
      },
      userMenuParamBean: {
        showDialog: false,
        roleId:-1,
        selectedItems: [],
      },
      //权限
      allRolePermissionData: [],//系统所有菜单树数据
      rolePermissionTreeProps: {
        children: 'children',
        label: 'menuName'
      },
      rolePermissionParamBean: {
        showDialog: false,
        roleId:-1,
        selectedItems: [],
      },
    };
  },
  created () {
    this.handleList();
  },
  watch: {},
  mounted () { },
  computed: {
    ...mapGetters(['permission', 'menuAll']),
  },
  props: [],
  methods: {
    /**
     * @title 菜单更新
     *
     **/
    handleUserMenuUpdate () {
      let checkMenuIds = [].concat(this.userMenuParamBean.selectedItems);
      let allUserMenuParams = {roleId: this.userMenuParamBean.roleId, ids: checkMenuIds};
      setRoleMenu(allUserMenuParams).then(() => {
        this.$message.success(this.$t("commHandle.addSuccTip"));
        this.userMenuParamBean.showDialog = false;
      });
    },
    /**
     * @title 菜单选择
     *
     **/
    handleUserMenuCheckChange (data, checked) {
      if (checked) {
        this.userMenuParamBean.selectedItems.push(data.id);
      } else {
        this.userMenuParamBean.selectedItems.splice(this.userMenuParamBean.selectedItems.indexOf(data.id), 1);
      }
    },
    /**
     * @title 设置用户菜单
     */
    toSetRoleMenu () {
      let row = this.getSelectOneData();
      if(!row)return;
      this.getAllMenuTreeData();
      this.userMenuParamBean.showDialog = true;
      this.userMenuParamBean.roleId = row.id;
      let allParams = {roleId: row.id};
      readRoleMenu(allParams).then(res => {
          // this.allSysMenuTreeData = res.data.allMenuList;
          this.userMenuParamBean.selectedItems = res.data.data;
          this.tableLoading = false;
      });
    },
    //获取系统所有菜单树
    getAllMenuTreeData () {
      // if(this.allSysMenuTreeData.size() > 0)return;
      readSystemMenuByTree({}).then(response => {
        const data = response.data;
        this.allSysMenuTreeData = data.data;
      })
    },

    /**
     * @title 权限更新
     *
     **/
    handleRolePermissionUpdate () {
      let checkMenuIds = [].concat(this.rolePermissionParamBean.selectedItems);
      let allUserMenuParams = {id: this.rolePermissionParamBean.roleId, ids: checkMenuIds};
      setRolePermission(allUserMenuParams).then(() => {
        this.$message.success(this.$t("commHandle.addSuccTip"));
        this.rolePermissionParamBean.showDialog = false;
      });
    },
    /**
     * @title 权限选择
     *
     **/
    handleRolePermissionCheckChange (data, checked) {
      if((data.id + '').length > 5){
        console.info('切换按钮ID['+data.id+']是否选中'+checked);
        this.unique(this.rolePermissionParamBean.selectedItems);
        if (checked) {
          this.rolePermissionParamBean.selectedItems.push(data.id);
        } else {
          this.rolePermissionParamBean.selectedItems.splice(this.rolePermissionParamBean.selectedItems.indexOf(data.id), 1);
        }
        console.info(this.rolePermissionParamBean.selectedItems);
      }
    },
    unique(arr) {
      var result = [], hash = {};
      for (var i = 0, elem; (elem = arr[i]) != null; i++) {
          if (!hash[elem]) {
              result.push(elem);
              hash[elem] = true;
          }
      }
      return result; 
    },
    /**
     * @title 设置角色权限
     */
    toSetRolePermission () {
      let row = this.getSelectOneData();
      if(!row)return;
      this.getAllRolePermission();
      this.rolePermissionParamBean.showDialog = true;
      this.rolePermissionParamBean.roleId = row.id;
      let allParams = {roleId: row.id};
      readRolePermission(allParams).then(res => {
          this.rolePermissionParamBean.selectedItems = res.data.data;
          this.tableLoading = false;
      });
    },

    //获取系统所有权限树
    getAllRolePermission () {
      // if(this.allRolePermissionData.size() > 0)return;
      readSystemMenuWhtiBtnsByTree({}).then(response => {
        const data = response.data;
        this.allRolePermissionData = data.data;
      })
    },

    /**
     * @title 获取数据
     * @detail 赋值为tableData表格即可
     *
     **/
    handleList () {
      this.tableLoading = true;
      let searchParam = this.tableSearch;
      let pageParams = {pageIndex:this.pageBeanModel.currentPage,pageSize:this.pageBeanModel.pageSize}
      let allParams = Object.assign(searchParam, pageParams);
      readSystemRoleByPage(allParams).then(res => {
        const data = res.data;
        this.tableData = data.data;
        this.pageBeanModel.total = data.total;
        this.pageBeanModel.currentPage = data.current;
        this.tableLoading = false;
      });
    },
    /**
     * @title 数据添加
     * @param row 为当前的数据
     * @param done 为表单关闭函数
     *
     **/
    handleSave (row, done,loading) {
      addSystemRole(row).then(() => {
         this.$message.success('添加成功');
         done();
         this.handleList();
        }).catch(() => {
          loading();
      })
    },
    handleRowEdit () {
      let row = this.getSelectOneData();
      if(!row)return;
      this.handleEdit(row, -1);
    },
    handleEdit (row, index) {
      this.$refs.crud.rowEdit(row, index);
    },
    /**
     * @title 数据更新
     * @param row 为当前的数据
     * @param index 为当前更新数据的行数
     * @param done 为表单关闭函数
     * @param loading 为表单关闭处理中的函数
     **/
    handleUpdate (row,index,done,loading) {
      console.info(index);
      editSystemRole(row).then(()=> {
         this.$message.success('修改成功');
         done();
         this.handleList();
        }).catch(() => {
          loading();
      })
    },
    handleRowDel () {
      let row = this.getSelectOneData();
      if(!row)return;
      this.handleDel(row, -1);
    },
    /**
     * @title 数据删除
     * @param row 为当前的数据
     * @param index 为当前更新数据的行数
     *
     **/
    handleDel (row, index) {
      this.$confirm(`是否确认删除账号为${row.roleName}的用户`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        delSystemRole(row.id).then(() => {
          this.$message.success('删除成功');
          console.log('删除成功==>' + index)
          this.handleList();
          }).catch(() => {
        })
      })
      .catch(() => { });
    },

    /**公共方法开始**/
    handlerefreshChange (pageBeanModel) {
      console.info(pageBeanModel);
      this.handleList();
    },
    handlePageCurrentChange (currentPage) {
      this.pageBeanModel.currentPage = currentPage;
      this.handleList();
    },
    handlePageSizeChange (pageSize) {
      this.pageBeanModel.pageSize = pageSize;
      this.pageBeanModel.currentPage = 1;
      this.handleList();
    },
    handleSearchChange (form) {
      this.tableSearch = form;
      this.handleList();
    },
    handleSelectionChange (val) {
      this.tableRow = val;
    },
    /**
     * @获取选择的一行数据
     */
    getSelectOneData(){
      if (validatenull(this.tableRow)) {
        this.$notify({
          showClose: true,
          message: '请选择一行数据',
          type: 'error',
        });
        return false;
      } else if (this.tableRow.length > 1) {
        this.$notify({
          showClose: true,
          message: '请选择一行数据，不要选择多行',
          type: 'error',
        });
        return false;
      }
      return this.tableRow[0];
    },
    formatJson (filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        }),
      );
    },
    tableRowClassName ({ rowIndex }) {
      if (rowIndex === 1) {
        return 'warning-row';
      } else if (rowIndex === 3) {
        return 'success-row';
      }
      return '';
    },
    tip (msg) {
      this.$notify({
        message: msg || '点击事件',
      });
    },
    /**公共方法结束**/
  },
};
</script>

<style lang="scss">
@import "@/styles/system.scss";
</style>